package com.example.ymm.modules1.service.dd.iot;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.ymm.exception.YmException;
import com.example.ymm.model.TableList;
import com.example.ymm.util.*;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

/**
 * 亮灯系统请求类
 * @author zeymo
 */
@Slf4j
@Service
public class IotHttpUtil extends HttpClientUtil {


    @Value("${iot.domain}")
    private String domain;

    @Value("${spring.profiles.active}")
    String PD_MATCH;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    IotAccessTokenService iotAccessTokenService;

    public JSONObject createHeader(){
        String accessToken = iotAccessTokenService.getAccessToken();
        JSONObject header = new JSONObject();
        header.put("Authorization", accessToken);
        return header;
    }

    /**
     * get 获取详情
     * @param url
     * @param param
     * @return
     */
    public JSONObject getDetail(String url, JSONObject param){
        String s = httpGet(domain+url, param, createHeader());
        JSONObject jsonNode=null;
        JSONObject data=null;
        try {
            if(UtilValidate.isNotEmpty(s)){
                jsonNode = JSONObject.parseObject(s);
                Integer code = jsonNode.getInteger("code");
                String msg = jsonNode.getString("msg");
                if(code==200){
                    data=jsonNode.getJSONObject("data");
                }else{
                    throw new YmException("code="+code+",msg="+msg);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return data;
    }

    /**
     * get 获取列表
     * @param url
     * @param param
     * @return
     */
    public TableList<JSONObject> getList(String url, JSONObject param){
        String s = httpGet(domain+url, param, createHeader());
        JSONObject jsonNode=null;
        TableList<JSONObject> tableList=new TableList<>();
        if(UtilValidate.isNotEmpty(s)){
            jsonNode = JSONObject.parseObject(s);
            Integer code = jsonNode.getInteger("code");
            String msg = jsonNode.getString("msg");
            Long total = 0l;
            if(jsonNode.containsKey("total")){
                total = jsonNode.getLong("total");
            }
            if(code==200){
                JSONArray jsonArray =null;
                if(jsonNode.containsKey("rows")){
                    jsonArray = jsonNode.getJSONArray("rows");
                }
                if(jsonNode.containsKey("data")){
                    jsonArray = jsonNode.getJSONArray("data");
                }

                List<JSONObject> list=jsonArray.toJavaList(JSONObject.class);
                tableList.setTotalResult(total);
                tableList.setList(list);
            }else{
                throw new YmException("code="+code+",msg="+msg);
            }
        }
        return tableList;
    }

    public JSONObject httpPost(String url, JSONObject param){
        String s = httpPost(domain+url, param, createHeader());
        JSONObject jsonNode=null;
        JSONObject data=null;
        try {
            if(UtilValidate.isNotEmpty(s)){
                jsonNode = JSONObject.parseObject(s);
                Integer code = jsonNode.getInteger("code");
                String msg = jsonNode.getString("fieldErrors");
                if(code==200){
//                    data=jsonNode.getJSONObject("data");
                }else if(code==401){
                    log.info("---亮灯token失效");
                    String tokenKey = RedisKeyManager.iot_access_token;
                    String lockKey = RedisKeyManager.iot_access_lock;
                    redisUtil.remove(tokenKey);
                    redisUtil.remove(lockKey);
                    return httpPost(url,param);
                }else{
                    throw new YmException(msg);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return jsonNode;
    }

    public JSONObject httpPostStr(String url, String arrStr){
        String s = httpPostStr(domain+url, arrStr, createHeader());
        JSONObject jsonNode=null;

        if(UtilValidate.isNotEmpty(s)){
            jsonNode = JSONObject.parseObject(s);
            Integer code = jsonNode.getInteger("code");
            String msg = jsonNode.getString("fieldErrors");
            if(code==200){
              //  data=jsonNode.getJSONObject("data");
            }else if(code==401){
                log.info("---亮灯token失效");
                String tokenKey = RedisKeyManager.iot_access_token;
                String lockKey = RedisKeyManager.iot_access_lock;
                redisUtil.remove(tokenKey);
                redisUtil.remove(lockKey);
                return httpPostStr(url,arrStr);
            }else{
                log.error("--亮灯接口失败:"+s);
                EmailUtil.sendEmail("1055162826@qq.com","发送亮灯接口异常，环境:"+PD_MATCH,s);

                throw new YmException(msg);
            }
        }
        return jsonNode;
    }


    public JSONObject httpPut(String url, JSONObject param){
        String s = httpPut(domain+url, param, createHeader());
        JSONObject jsonNode=null;
        JSONObject data=null;
        try {
            if(UtilValidate.isNotEmpty(s)){
                jsonNode = JSONObject.parseObject(s);
                Integer code = jsonNode.getInteger("code");
                String msg = jsonNode.getString("msg");
                if(code==200){
                    data=jsonNode.getJSONObject("data");
                }else{
                    throw new YmException("code="+code+",msg="+msg);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return data;
    }

    public JSONObject httpDelete(String url, JSONObject param){
        String s = httpDelete(domain+url, param, createHeader());
        JSONObject jsonNode=null;
        JSONObject data=null;
        try {
            if(UtilValidate.isNotEmpty(s)){
                jsonNode = JSONObject.parseObject(s);
                Integer code = jsonNode.getInteger("code");
                String msg = jsonNode.getString("msg");
                if(code==200){
                    data=jsonNode.getJSONObject("data");
                }else{
                    throw new YmException("code="+code+",msg="+msg);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return data;
    }


    public String httpPostLogin(JSONObject param){
        SSLUtils.disableSSLVerification();
        String s = httpPost(domain+"/nonCodeLogin", param, null);
        JSONObject jsonNode=null;
        String token=null;
        try {
            log.info("--登录亮灯返回结果："+s);
            if(UtilValidate.isNotEmpty(s)){
                jsonNode = JSONObject.parseObject(s);
                Integer code = jsonNode.getInteger("code");
                String msg = jsonNode.getString("fieldErrors");
                if(code==200){
                    token=jsonNode.getString("token");
                }else{
                    throw new YmException(msg);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return token;
    }
}
